<?php
require $_SERVER['DOCUMENT_ROOT'].'/../_core/common.php';

$msg = array();

//权限验证
if( Role::init() == false ){
	$msg['error'] = false;
	$msg['string'] = '权限不足！';
	$myjson = json_encode($msg); 
	echo $myjson; 
	exit;
}

require $_SERVER['DOCUMENT_ROOT'].'/../_interface/category.php';


$db = new DB('news');

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

//查栏目
$category_sql = 'select id,title,parent_id,top_id,child_id from categories where id='.$id.' and is_del=1 limit 1';
$category_rs = $db->query($category_sql)->getOne();

if( $category_rs['id'] <= 0 ){//id不存在
	$msg['error'] = false;
	$msg['string'] = '参数有误！';
}elseif( $category_rs['child_id'] != '' ){
	$msg['error'] = false;
	$msg['string'] = '请先删除子级栏目！';
}

//查文章
$news_sql = 'select title_id from news where category_id='.$id.' and is_del=1';
$news_total = $db->query($news_sql)->getCount();
if( $news_total < 1 ){
	if($category_rs['parent_id']==0 && $category_rs['top_id']==0){//是顶级栏目
		//直接更新is_del字段
		$data = array('is_del'=>2);
		$db->table('categories')->where('id='.$id)->update($data)->run();
		
		$msg['error'] = true;
		$msg['string'] = '删除《'.$category_rs['title'].'》栏目成功!';
	}else{//不是顶级栏目
		$category = new Category($db);

		//更新当前id记录的原来父级的child_id字段
		$error = false;
		if( !$category -> child_del($id,$id) ){
			$error = true;
		}

		if($error === true){
			$msg['error'] = false;
			$msg['string'] = '参数有误！';
		}else{
			//更新is_del字段
			$data = array('is_del'=>2);
			$db->table('categories')->where('id='.$id)->update($data)->run();
			
			$msg['error'] = true;
			$msg['string'] = '成功删除《'.$category_rs['title'].'》栏目!';
		}
	}
}else{
	$msg['error'] = false;
	$msg['string'] = '栏目下有 '.$news_total.' 篇文章，请先删除文章！';
}

$myjson = json_encode($msg); 
echo $myjson; 